package servlet;

import entity.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置解码方式
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //获取值
        String name=request.getParameter("userId"); //账号
        String pwd=request.getParameter("passWord"); //密码

        HttpSession session=request.getSession();

        //创建用户的数据访问对象
        UserService userService=new UserServiceImpl();
        User user=userService.login(name,pwd);

        //判断
        if (user!=null){
            session.setAttribute("user",user);
            session.setMaxInactiveInterval(15*60);
            response.sendRedirect(request.getContextPath()+"/BlogServlet?opr=HomeBlogList");

                   /* alert("登录成功！")
            window.location="blog_control.jsp?opr=HomeBlogList";*/

        }else {
                   /* alert("账号或密码输入错误！请重新输入！")
            window.location="../pages/login.jsp"*/
            response.sendRedirect(request.getContextPath()+"/pages/login.jsp");
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
